package com.h2.ref.server.auth.token;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;


public final class AuthTokenUtils {
   
   private static final Logger LOG = LoggerFactory.getLogger(AuthTokenUtils.class);
   
   private static final SecureRandom RANDOM = new SecureRandom();
   
   public static final Character[] NUMERIC = { '0', '1', '2', '3', '4', '5', '6',
         '7', '8', '9' };

   public static final Character[] LOWER_CASE_ALPHA = { 'a', 'b', 'c', 'd',
         'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
         's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };

   public static final Character[] UPPER_CASE_ALPHA = { 'A', 'B', 'C', 'D',
         'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
         'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
   
   /*
    * We intentionally do not add upper case O, lower case l, lower case
    * o, in order to avoid confusion with numerals zero or 1.
    */
   public static Character[] MIXED_CASE_ALPHA_NUMERIC_HUMAN_READABLE;
   
   public static Character[] MIXED_CASE_ALPHA_NUMERIC;
   {
      List<Character> characters = new ArrayList<Character>(
            NUMERIC.length + LOWER_CASE_ALPHA.length + UPPER_CASE_ALPHA.length);
      for (char c : NUMERIC) {
         characters.add(c);
      }
      for (char c : LOWER_CASE_ALPHA) {
         characters.add(c);
      }
      for (char c : UPPER_CASE_ALPHA) {
         characters.add(c);
      }
      MIXED_CASE_ALPHA_NUMERIC = (Character[]) characters.toArray();
      
      
      characters.removeAll(Lists.newArrayList('o', '0', 'O', 'l', '1', 'I'));
      MIXED_CASE_ALPHA_NUMERIC_HUMAN_READABLE =
            (Character[]) characters.toArray();
   }
   
   private AuthTokenUtils() {
      LOG.debug("Public/Default constructors are not allowed in utils classes");
   }
   
   private static String generateToken(SecureRandom random, Character[] array,
         int tokenSize) {
      int charArraySize = array.length;
      StringBuilder builder = new StringBuilder();
      for (int i = 0; i < tokenSize; i++) {
         builder.append(array[random.nextInt(charArraySize)]);
      }
      return builder.toString();
   }
   
   public static String mixedCaseAlphaNumericToken(int tokenSize) {
      return generateToken(RANDOM, MIXED_CASE_ALPHA_NUMERIC, tokenSize);
   }
   
   /*
    * This overload is provided in case user of the utils class wants to
    * pass in a custom implementation of SecureRandom class.
    */
   public static String mixedCaseAlphaNumericToken(SecureRandom random, int tokenSize) {
      return generateToken(random, MIXED_CASE_ALPHA_NUMERIC, tokenSize);
   }
   
}
